home *** CD-ROM | disk | FTP | other *** search
/ PC World 2008 September / PCWorld_2008-09_cd.bin / v cisle / sadanastroju / signature_switch-1.6.1-tb.xpi / chrome / signatureswitch.jar / content / signatureswitch.js < prev    next >
Text File  |  2008-03-07  |  31KB  |  921 lines

  1. var ss_loadStatus = false;
  2. var ss_initStatus = false;
  3.  
  4. var ss_signature = new Array();
  5. var ss_startNode = null;
  6.  
  7. var ss_autoSwitch = false;
  8. var ss_autoSwitchAddresses = new Array();
  9. var ss_autoSwitchNewsgroups = new Array();
  10. var ss_autoSwitchMailinglists = new Array();
  11.  
  12. var ss_cycleIndex = null;
  13.  
  14. var ss_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.signatureswitch.");
  15.  
  16. var ss_main = {
  17.  
  18.     signatureSwitch : function()
  19.     {
  20.         var currentEditor = GetCurrentEditor();
  21.         var currentEditorDom = currentEditor.rootElement;
  22.         var currentEditorDomChilds = currentEditorDom.childNodes;
  23.  
  24.         var initialRange = currentEditor.selection.getRangeAt(0).cloneRange();
  25.  
  26.         currentEditor.beginTransaction();
  27.  
  28.         if (ss_signature.length > 0)
  29.         {
  30.             ss_main.insertSignature(currentEditor, currentEditorDom, currentEditorDomChilds);
  31.         }
  32.         else
  33.         {
  34.             if (ss_main.searchSignature(currentEditorDomChilds))
  35.                 ss_main.removeSignature(currentEditor);
  36.         }
  37.  
  38.         currentEditor.selection.removeAllRanges();
  39.         currentEditor.selection.addRange(initialRange);
  40.  
  41.         currentEditor.endTransaction();
  42.     },
  43.  
  44.     searchSignature : function(nodes)
  45.     {
  46.         var node = null;
  47.         var nodeText = "";
  48.  
  49.         for (var i = (nodes.length - 1) ; i >= 0 ; i--)
  50.         {
  51.             node = nodes[i];
  52.  
  53.             if (node.hasChildNodes())
  54.             {
  55.                 if (node.hasAttributes())
  56.                 {
  57.                     if (node.getAttribute("class") == "moz-signature")
  58.                     {
  59.                         ss_startNode = node;
  60.                         return true;
  61.                     }
  62.                 }
  63.                 else
  64.                 {
  65.                     if (ss_main.searchSignature(node.childNodes))
  66.                         return true;
  67.                 }
  68.             }
  69.  
  70.             try
  71.             {
  72.                 nodeText = node.nodeValue;
  73.  
  74.                 if ((nodeText.substring(0, 3) == "-- ") && (nodeText.length <= 5))
  75.                 {
  76.                     ss_startNode = node;
  77.                     return true;
  78.                 }
  79.             }
  80.             catch (e) {}
  81.         }
  82.  
  83.         return false;
  84.     },
  85.  
  86.     removeSignature : function(editor)
  87.     {
  88.         if (GetCurrentEditorType() == "textmail")
  89.         {
  90.             var currentNode = ss_startNode;
  91.             var nextNode;
  92.  
  93.             while (currentNode)
  94.             {
  95.                 ss_signature.push(currentNode.cloneNode(true));
  96.                 nextNode = currentNode.nextSibling;
  97.                 editor.deleteNode(currentNode);
  98.                 currentNode = nextNode;
  99.             }
  100.         }
  101.         else
  102.         {
  103.             ss_signature.push(ss_startNode.cloneNode(true));
  104.             editor.deleteNode(ss_startNode);
  105.         }
  106.     },
  107.  
  108.     insertSignature : function(editor, element, nodes)
  109.     {
  110.         ss_signature.reverse();
  111.  
  112.         while (ss_signature.length > 0)
  113.         {
  114.             editor.insertNode(ss_signature.pop(), element, nodes.length);
  115.         }
  116.  
  117.         ss_signature = new Array();
  118.     },
  119.  
  120.     cycleSignature : function()
  121.     {
  122.         var maxSigIdx = ss_main.loadSignatureProperty(0).length - 1;
  123.  
  124.         if (ss_cycleIndex == maxSigIdx || ss_cycleIndex > maxSigIdx)
  125.            ss_cycleIndex = 0;
  126.         else
  127.            ss_cycleIndex ++;
  128.  
  129.         ss_main.loadSignature(ss_cycleIndex, true);
  130.     },
  131.  
  132.     loadSignature : function(idx, del)
  133.     {
  134.         var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  135.         var filePath = ss_main.replaceDirectoryVariable(ss_main.loadSignatureProperty(1)[idx]);
  136.  
  137.         file.initWithPath(filePath);
  138.  
  139.         if (!file.exists())
  140.             return;
  141.  
  142.         var shouldRunPreloadExecutable = ss_prefs.getBoolPref("preloadexecutable");
  143.  
  144.         if (shouldRunPreloadExecutable)
  145.             ss_main.runPreLoadExecutable(filePath);
  146.  
  147.         var signature = ss_main.loadFile(file);
  148.  
  149.         if (signature.indexOf("\r\n") > -1)
  150.             signature = signature.split("\r\n").join("\n");
  151.  
  152.         // special treatment for those Apple-fanboys
  153.         if (signature.indexOf("\r") > -1)
  154.             signature = signature.split("\r").join("\n");
  155.  
  156.         if (signature.indexOf("\n%\n") > -1)
  157.         {
  158.             var fpIndex = signature.indexOf("\n$\n");
  159.             var fpContent = null;
  160.  
  161.             if (fpIndex > -1)
  162.             {
  163.                 fpContent = ss_main.dehybrid(signature.substring(0, fpIndex));
  164.                 signature = signature.substr(fpIndex + 3);
  165.             }
  166.  
  167.             var fortuneCookies = signature.split("\n%\n");
  168.  
  169.             signature = ss_main.dehybrid(fortuneCookies[ss_main.rand(fortuneCookies.length) - 1] + "\n");
  170.  
  171.             if (fpContent)
  172.                 signature = fpContent + "\n" + signature;
  173.         }
  174.         else
  175.         {
  176.             signature = ss_main.dehybrid(signature);
  177.         }
  178.  
  179.         var currentEditor = GetCurrentEditor();
  180.         var currentEditorDom = currentEditor.rootElement;
  181.         var currentEditorDomChilds = currentEditorDom.childNodes;
  182.  
  183.         var initialRange = currentEditor.selection.getRangeAt(0).cloneRange();
  184.         var initialModCount = currentEditor.getModificationCount();
  185.  
  186.         var hasSignature = ss_main.searchSignature(currentEditorDomChilds);
  187.  
  188.         currentEditor.beginTransaction();
  189.  
  190.         if (hasSignature && del)
  191.         {
  192.             ss_main.removeSignature(currentEditor);
  193.             currentEditorDomChilds = currentEditorDom.childNodes;
  194.         }
  195.  
  196.         currentEditor.endOfDocument();
  197.  
  198.         var newRange = currentEditor.selection.getRangeAt(0).cloneRange();
  199.         var editorIsEmpty = ss_main.trim(ss_main.concatenateNodeValues(currentEditorDomChilds)) == "";
  200.  
  201.         if ((newRange.startOffset == 1 && !editorIsEmpty) || (initialModCount == 0 && !hasSignature))
  202.             currentEditor.insertLineBreak();
  203.  
  204.         if (GetCurrentEditorType() == "textmail")
  205.         {
  206.             if (signature.indexOf("-- \n") == -1)
  207.                 signature = "-- \n" + signature;
  208.  
  209.             currentEditor.insertText(signature);
  210.         }
  211.         else
  212.         {
  213.             if (signature.indexOf("-- \n") == -1 && signature.indexOf("-- <") == -1)
  214.                 signature = "-- <br>" + signature ;
  215.  
  216.             signature = "<div class=\"moz-signature\">" + signature + "</div>";
  217.  
  218.             currentEditor.insertHTML(signature);
  219.         }
  220.  
  221.         currentEditor.endTransaction();
  222.  
  223.         currentEditor.selection.removeAllRanges();
  224.         currentEditor.selection.addRange(initialRange);
  225.  
  226.         ss_main.sanitize();
  227.         ss_main.sanitize();
  228.     },
  229.  
  230.     runPreLoadExecutable : function(signaturePath)
  231.     {
  232.         var preLoadExecutable = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  233.         var preLoadExecutablePath = ss_prefs.getComplexValue("preloadexecutablepath", Components.interfaces.nsISupportsString).data;
  234.         var preLoadExecutableWait = ss_prefs.getBoolPref("preloadexecutablewait");
  235.  
  236.         preLoadExecutable.initWithPath(preLoadExecutablePath);
  237.  
  238.         if (!preLoadExecutable.exists())
  239.             return false;
  240.  
  241.         Recipients2CompFields(gMsgCompose.compFields);
  242.  
  243.         var preLoadExecutableArgs = new Array(signaturePath);
  244.         preLoadExecutableArgs = preLoadExecutableArgs.concat(document.getElementById("msgSubject").value);
  245.         preLoadExecutableArgs = preLoadExecutableArgs.concat([getCurrentIdentity().email]);
  246.         preLoadExecutableArgs = preLoadExecutableArgs.concat(ss_main.getAddressesFromCompField(gMsgCompose.compFields.to));
  247.         preLoadExecutableArgs = preLoadExecutableArgs.concat(ss_main.getAddressesFromCompField(gMsgCompose.compFields.cc));
  248.         preLoadExecutableArgs = preLoadExecutableArgs.concat(ss_main.getAddressesFromCompField(gMsgCompose.compFields.bcc));
  249.         preLoadExecutableArgs = preLoadExecutableArgs.concat(gMsgCompose.compFields.newsgroups.split(","));
  250.  
  251.         var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
  252.         process.init(preLoadExecutable);
  253.         process.run(preLoadExecutableWait, preLoadExecutableArgs, preLoadExecutableArgs.length);
  254.     },
  255.  
  256.     concatenateNodeValues : function(nodes)
  257.     {
  258.         var nodeValue = "";
  259.         var nodeValues = "";
  260.  
  261.         for (var i = (nodes.length - 1) ; i >= 0 ; i--)
  262.         {
  263.             if (nodes[i].hasChildNodes())
  264.                 nodeValues = nodeValues + ss_main.concatenateNodeValues(nodes[i].childNodes);
  265.  
  266.             try
  267.             {
  268.                 nodeValue = nodes[i].nodeValue;
  269.  
  270.                 if (nodeValue)
  271.                     nodeValues = nodeValues + nodeValue;
  272.             }
  273.             catch (e) {}
  274.         }
  275.  
  276.         return nodeValues;
  277.     },
  278.  
  279.     trim : function(inString)
  280.     {
  281.         inString = inString.replace( /^\s+/g, "" );
  282.         inString = inString.replace( /\s+$/g, "" );
  283.  
  284.         return inString;
  285.     },
  286.  
  287.     sanitize : function()
  288.     {
  289.         ss_initStatus = false;
  290.         ss_signature = new Array();
  291.         ss_startNode = null;
  292.     },
  293.  
  294.     onLoad : function()
  295.     {
  296.         if (ss_loadStatus)
  297.             return;
  298.  
  299.         ss_main.ensurePrefs();
  300.         ss_main.registerShortcuts();
  301.         ss_main.modifyAddressingWidget();
  302.         ss_main.init();
  303.  
  304.         ss_loadStatus = true;
  305.     },
  306.  
  307.     ensurePrefs : function()
  308.     {
  309.         var prefs = [       "shortcut_onoff_key",
  310.                             "shortcut_onoff_modifier_accel",
  311.                             "shortcut_onoff_modifier_alt",
  312.                             "shortcut_onoff_modifier_control",
  313.                             "shortcut_onoff_modifier_meta",
  314.                             "shortcut_onoff_modifier_shift",
  315.                             "shortcut_cycle_key",
  316.                             "shortcut_cycle_modifier_accel",
  317.                             "shortcut_cycle_modifier_alt",
  318.                             "shortcut_cycle_modifier_control",
  319.                             "shortcut_cycle_modifier_meta",
  320.                             "shortcut_cycle_modifier_shift",
  321.                             "offbydefault",
  322.                             "contextmenu",
  323.                             "encoding",
  324.                             "preloadexecutable",
  325.                             "preloadexecutablepath",
  326.                             "preloadexecutablewait",
  327.                             "initdelay",
  328.                             "autoswitchpriority"             ];
  329.  
  330.         for (var i = 0; i < prefs.length; i++)
  331.         {
  332.             if (ss_prefs.getPrefType(prefs[i]) == ss_prefs.PREF_INVALID)
  333.             {
  334.                 ss_main.openOptions(true);
  335.                 return;
  336.              }
  337.         }
  338.     },
  339.  
  340.     init : function()
  341.     {
  342.         if (ss_initStatus)
  343.             return;
  344.  
  345.         var defaultsignature;
  346.         var offbydefault;
  347.         var contextmenu;
  348.         var initdelay;
  349.  
  350.         try
  351.         {
  352.             defaultsignature = parseInt(ss_prefs.getCharPref("defaultsignature"));
  353.             offbydefault = ss_prefs.getBoolPref("offbydefault");
  354.             contextmenu = ss_prefs.getBoolPref("contextmenu");
  355.             initdelay = parseInt(ss_prefs.getCharPref("initdelay"));
  356.         }
  357.         catch (e)
  358.         {
  359.             defaultsignature = -1;
  360.             offbydefault = false;
  361.             contextmenu = true;
  362.             initdelay = 1000;
  363.         }
  364.  
  365.         var ctxmenu = document.getElementById("SignatureSwitchContext");
  366.  
  367.         ctxmenu.setAttribute("hidden", !contextmenu);
  368.  
  369.         ss_autoSwitchAddresses = ss_main.loadSignatureProperty(3);
  370.         ss_autoSwitchNewsgroups = ss_main.loadSignatureProperty(4);
  371.         ss_autoSwitchMailinglists = ss_main.loadSignatureProperty(5);
  372.  
  373.         ss_autoSwitch = ( ss_main.checkAutoSwitchArray(ss_autoSwitchAddresses)    ||
  374.                           ss_main.checkAutoSwitchArray(ss_autoSwitchNewsgroups)   ||
  375.                           ss_main.checkAutoSwitchArray(ss_autoSwitchMailinglists) );
  376.  
  377.         if ((defaultsignature > -1) || offbydefault || ss_autoSwitch)
  378.             setTimeout("ss_main.delayedInit(" + defaultsignature + ", " + offbydefault + ")", initdelay);
  379.  
  380.         ss_initStatus = true;
  381.     },
  382.  
  383.     delayedInit : function(defaultsignature, offbydefault)
  384.     {
  385.         var hasDefaultSignature = defaultsignature > -1;
  386.         var hasAccountSignature = false;
  387.         var autoSwitched = ss_main.autoSwitch();
  388.  
  389.         ss_cycleIndex = (hasDefaultSignature) ? defaultsignature : 0;
  390.  
  391.         try
  392.         {
  393.             hasAccountSignature = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("mail.identity." + document.getElementById("msgIdentity").value + ".").getBoolPref("attach_signature");
  394.         }
  395.         catch (e) {}
  396.  
  397.         if (!autoSwitched && hasDefaultSignature)
  398.             ss_main.loadSignature(defaultsignature, (hasAccountSignature || ss_initStatus));
  399.  
  400.         if (offbydefault && (hasAccountSignature || hasDefaultSignature || autoSwitched))
  401.             ss_main.signatureSwitch();
  402.     },
  403.  
  404.     initMenuPopup : function(element)
  405.     {
  406.         var menuPopup = document.getElementById("SignatureSwitchMenuPopup-" + element);
  407.  
  408.         ss_main.removeMenuItems(menuPopup);
  409.  
  410.         if (element != "toolbar")
  411.         {
  412.             ss_main.insertOnOffItem(menuPopup, ss_main.getLocalizedMessage("menuItem.onOff"), ss_main.getLocalizedMessage("toolTip.onOff"), "SignatureSwitchKey");
  413.             menuPopup.appendChild(document.createElement("menuseparator"));
  414.         }
  415.  
  416.         var descriptionData = ss_main.loadSignatureProperty(0);
  417.         var pathData = ss_main.loadSignatureProperty(1);
  418.  
  419.         var description;
  420.         var path;
  421.         var validation;
  422.         var shortcut;
  423.  
  424.         for (var i = 0; i < descriptionData.length; i++)
  425.         {
  426.             description = descriptionData[i];
  427.             path = ss_main.replaceDirectoryVariable(pathData[i]);
  428.             validation = ss_main.validateFile(path);
  429.             shortcut = document.getElementById("signatureswitch_shortcut_" + i);
  430.  
  431.             if (shortcut)
  432.                 shortcut = shortcut.id;
  433.  
  434.             ss_main.insertMenuItem(menuPopup, description, path, i, !validation, shortcut);
  435.         }
  436.  
  437.         if (descriptionData.length > 0)
  438.             menuPopup.appendChild(document.createElement("menuseparator"));
  439.  
  440.         ss_main.insertOptionsItem(menuPopup, ss_main.getLocalizedMessage("menuItem.options"), ss_main.getLocalizedMessage("toolTip.enterOptions"));
  441.     },
  442.  
  443.     registerShortcuts : function()
  444.     {
  445.         var shortcut;
  446.  
  447.         // common shortcuts ...
  448.  
  449.         var shortcut_names = new Array("onoff", "cycle");
  450.         var shortcut_name;
  451.  
  452.         var shortcut_key;
  453.         var shortcut_modifier_accel;
  454.         var shortcut_modifier_alt;
  455.         var shortcut_modifier_control;
  456.         var shortcut_modifier_meta;
  457.         var shortcut_modifier_shift;
  458.  
  459.         var shortcut_modifiers;
  460.  
  461.         while (shortcut_names.length > 0)
  462.         {
  463.             shortcut_name = shortcut_names.pop();
  464.  
  465.             try
  466.             {
  467.                 shortcut_key              = ss_prefs.getCharPref("shortcut_" + shortcut_name + "_key");
  468.                 shortcut_modifier_accel   = ss_prefs.getBoolPref("shortcut_" + shortcut_name + "_modifier_accel");
  469.                 shortcut_modifier_alt     = ss_prefs.getBoolPref("shortcut_" + shortcut_name + "_modifier_alt");
  470.                 shortcut_modifier_control = ss_prefs.getBoolPref("shortcut_" + shortcut_name + "_modifier_control");
  471.                 shortcut_modifier_meta    = ss_prefs.getBoolPref("shortcut_" + shortcut_name + "_modifier_meta");
  472.                 shortcut_modifier_shift   = ss_prefs.getBoolPref("shortcut_" + shortcut_name + "_modifier_shift");
  473.             }
  474.             catch (e)
  475.             {
  476.                 shortcut_key              = (shortcut_name == "onoff") ? "Y" : "C";
  477.                 shortcut_modifier_accel   = false;
  478.                 shortcut_modifier_alt     = false;
  479.                 shortcut_modifier_control = true;
  480.                 shortcut_modifier_meta    = false;
  481.                 shortcut_modifier_shift   = true;
  482.             }
  483.  
  484.             shortcut_modifiers = new Array();
  485.  
  486.             if (shortcut_modifier_accel)
  487.                 shortcut_modifiers.push("accel");
  488.             if (shortcut_modifier_alt)
  489.                 shortcut_modifiers.push("alt");
  490.             if (shortcut_modifier_control)
  491.                 shortcut_modifiers.push("control");
  492.             if (shortcut_modifier_meta)
  493.                 shortcut_modifiers.push("meta");
  494.             if (shortcut_modifier_shift)
  495.                 shortcut_modifiers.push("shift");
  496.  
  497.             shortcut = document.getElementById("SignatureSwitchKey_" + shortcut_name);
  498.             shortcut.setAttribute("key", shortcut_key);
  499.             shortcut.setAttribute("modifiers", shortcut_modifiers.join(","));
  500.         }
  501.  
  502.         // signature shortcuts ...
  503.  
  504.         var shortcutData = ss_main.loadSignatureProperty(2);
  505.         var shortcutKeyset = document.getElementById("SignatureSwitchShortcuts");
  506.         var shortcutString;
  507.  
  508.         for (var i = 0; i < shortcutData.length; i++)
  509.         {
  510.             shortcutString = shortcutData[i];
  511.  
  512.             // legacy support
  513.             if (shortcutString == "")
  514.                 shortcutString = " -----";
  515.  
  516.             shortcut = document.createElement("key");
  517.             shortcut.setAttribute("id", "signatureswitch_shortcut_" + i);
  518.  
  519.             shortcut_key = shortcutString.charAt(0);
  520.  
  521.             if (shortcut_key == " ")
  522.             {
  523.                 shortcut.setAttribute("key", "");
  524.                 shortcut.setAttribute("modifiers", "");
  525.                 shortcut.setAttribute("oncommand", "");
  526.             }
  527.             else
  528.             {
  529.                 shortcut_modifiers = new Array();
  530.  
  531.                 if (shortcutString.charAt(1) == "X")
  532.                     shortcut_modifiers.push("accel");
  533.                 if (shortcutString.charAt(2) == "X")
  534.                     shortcut_modifiers.push("alt");
  535.                 if (shortcutString.charAt(3) == "X")
  536.                     shortcut_modifiers.push("control");
  537.                 if (shortcutString.charAt(4) == "X")
  538.                     shortcut_modifiers.push("meta");
  539.                 if (shortcutString.charAt(5) == "X")
  540.                     shortcut_modifiers.push("shift");
  541.  
  542.                 shortcut.setAttribute("key", shortcut_key);
  543.                 shortcut.setAttribute("modifiers", shortcut_modifiers.join(","));
  544.                 shortcut.setAttribute("oncommand", "ss_main.loadSignature(" + i + ", true);");
  545.             }
  546.  
  547.             shortcutKeyset.appendChild(shortcut);
  548.         }
  549.     },
  550.  
  551.     modifyAddressingWidget : function()
  552.     {
  553.         var addressingWidget = document.getElementById("addressingWidget");
  554.  
  555.         addressingWidget.setAttribute("onkeydown", "ss_main.autoSwitch(); " + addressingWidget.getAttribute("onkeydown"));
  556.         addressingWidget.setAttribute("onkeyup", "ss_main.autoSwitch(); " + addressingWidget.getAttribute("onkeyup"));
  557.         addressingWidget.setAttribute("onclick", "ss_main.autoSwitch(); " + addressingWidget.getAttribute("onclick"));
  558.         addressingWidget.setAttribute("onblur", "ss_main.autoSwitch(); " + addressingWidget.getAttribute("onblur"));
  559.     },
  560.  
  561.     loadSignatureProperty : function(idx)
  562.     {
  563.         var dataString;
  564.         var items = new Array();
  565.  
  566.         try
  567.         {
  568.             dataString = ss_prefs.getComplexValue("signatures", Components.interfaces.nsISupportsString).data;
  569.  
  570.             if (dataString != "")
  571.             {
  572.                 var itemStrings = dataString.split("|");
  573.  
  574.                 var itemData;
  575.  
  576.                 for (var i = 0; i < itemStrings.length; i ++)
  577.                 {
  578.                     itemData = itemStrings[i].split("*");
  579.  
  580.                     items.push((itemData[idx]) ? itemData[idx] : "");
  581.                 }
  582.             }
  583.         }
  584.         catch (e) {}
  585.  
  586.         return items;
  587.     },
  588.  
  589.     loadFile : function(file)
  590.     {
  591.         var data = "";
  592.  
  593.         var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
  594.         var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  595.         var sconverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  596.  
  597.         try
  598.         {
  599.             fstream.init(file, 1, 0, false);
  600.             sstream.init(fstream);
  601.             data += sstream.read(-1);
  602.             sstream.close();
  603.             fstream.close();
  604.  
  605.             sconverter.charset = ss_prefs.getCharPref("encoding");
  606.             data = sconverter.ConvertToUnicode(data);
  607.         }
  608.         catch (e) {}
  609.  
  610.         return data;
  611.     },
  612.  
  613.     removeMenuItems : function(menu)
  614.     {
  615.         var children = menu.childNodes;
  616.  
  617.         for (var i = children.length - 1; i >= 0; i--)
  618.         {
  619.             menu.removeChild(children[i]);
  620.         }
  621.     },
  622.  
  623.     insertMenuItem : function(menu, label, tooltip, idx, disabled, key)
  624.     {
  625.         var item = document.createElement("menuitem");
  626.  
  627.         item.setAttribute("id", "signatureswitch_signature_" + idx);
  628.         item.setAttribute("label", label);
  629.         item.setAttribute("tooltiptext", tooltip);
  630.         item.setAttribute("oncommand", "ss_main.loadSignature(" + idx + ", true); event.stopPropagation();");
  631.         item.setAttribute("disabled", disabled);
  632.  
  633.         if (key)
  634.             item.setAttribute("key", key);
  635.  
  636.         menu.appendChild(item);
  637.     },
  638.  
  639.     insertOptionsItem : function(menu, label, tooltip)
  640.     {
  641.         var item = document.createElement("menuitem");
  642.  
  643.         item.setAttribute("id", "signatureswitch_openOptions");
  644.         item.setAttribute("label", label);
  645.         item.setAttribute("tooltiptext", tooltip);
  646.         item.setAttribute("oncommand", "ss_main.openOptions(false); event.stopPropagation();");
  647.         item.setAttribute("disabled", false);
  648.  
  649.         menu.appendChild(item);
  650.     },
  651.  
  652.     insertOnOffItem : function(menu, label, tooltip, key)
  653.     {
  654.         var item = document.createElement("menuitem");
  655.  
  656.         item.setAttribute("id", "signatureswitch_onOff");
  657.         item.setAttribute("label", label);
  658.         item.setAttribute("tooltiptext", tooltip);
  659.         item.setAttribute("oncommand", "ss_main.signatureSwitch(); event.stopPropagation();");
  660.         item.setAttribute("key", key);
  661.         item.setAttribute("disabled", false);
  662.  
  663.         menu.appendChild(item);
  664.     },
  665.  
  666.     replaceDirectoryVariable : function(path)
  667.     {
  668.         if (path.substring(0,1) != "%")
  669.              return path;
  670.  
  671.         var returnPath = path;
  672.  
  673.         try
  674.         {
  675.             var dirVar = path.substring(1, path.indexOf("%", 1));
  676.             returnPath = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get(dirVar, Components.interfaces.nsIFile).path + path.substring(path.indexOf("%", 1) + 1);
  677.         }
  678.         catch (e) {}
  679.  
  680.         return returnPath;
  681.     },
  682.  
  683.     validateFile : function(path)
  684.     {
  685.         var isValid = false;
  686.  
  687.         try
  688.         {
  689.             var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  690.             file.initWithPath(path);
  691.             isValid = file.isFile();
  692.         }
  693.         catch (e) {}
  694.  
  695.         return isValid;
  696.     },
  697.  
  698.     rand : function(n)
  699.     {
  700.         return (Math.floor(Math.random() * n + 1));
  701.     },
  702.  
  703.     getLocalizedMessage : function(msg)
  704.     {
  705.         return document.getElementById("signatureswitch.locale").getString(msg);
  706.     },
  707.  
  708.     openOptions : function(autosave)
  709.     {
  710.         return window.openDialog("chrome://signatureswitch/content/options.xul", "_blank", "chrome, modal, resizable=yes", autosave);
  711.     },
  712.  
  713.     fromChanged : function()
  714.     {
  715.         if ( parseInt(ss_prefs.getCharPref("defaultsignature")) > -1 &&
  716.              ss_main.searchSignature(GetCurrentEditor().rootElement.childNodes) )
  717.         {
  718.             GetCurrentEditor().beginTransaction();
  719.             ss_main.removeSignature(GetCurrentEditor());
  720.             GetCurrentEditor().endTransaction();
  721.         }
  722.  
  723.         ss_main.sanitize();
  724.         ss_main.init();
  725.     },
  726.  
  727.     autoSwitch : function()
  728.     {
  729.         if (!ss_autoSwitch)
  730.             return false;
  731.  
  732.         var priority = ss_prefs.getCharPref("autoswitchpriority");
  733.  
  734.         Recipients2CompFields(gMsgCompose.compFields);
  735.  
  736.         var emailAddresses = ss_main.getAddressesFromCompField(gMsgCompose.compFields.to);
  737.         var newsgroups = gMsgCompose.compFields.newsgroups;
  738.         var mailinglists = new Array();
  739.  
  740.         var rx = null;
  741.         var rx_wildcard = null;
  742.  
  743.         var chosenAutoSwitchSignatureForAddresses = -1;
  744.         var chosenAutoSwitchSignatureForNewsgroups = -1;
  745.         var chosenAutoSwitchSignatureForMailinglists = -1;
  746.  
  747.         if (emailAddresses.length > 0 && ss_autoSwitchAddresses.length > 0)
  748.         {
  749.             var rx_user = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
  750.             var rx_domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
  751.  
  752.             rx = "^" + rx_user + "\@" + rx_domain + "$";
  753.             rx_wildcard = "[a-zA-Z0-9._-]*";
  754.  
  755.             var address;
  756.             var addresses = new Array();
  757.  
  758.             for (var i = 0; i < emailAddresses.length; i++)
  759.             {
  760.                 address = emailAddresses[i];
  761.  
  762.                 if (address.charAt(0) == "\"" && address.charAt(address.length - 1) == "\"")
  763.                    mailinglists.push(address.substring(1, address.length - 1));
  764.                 else
  765.                    addresses.push(address);
  766.             }
  767.  
  768.             chosenAutoSwitchSignatureForAddresses = ss_main.findMatchingAutoSwitchSignature(addresses, ss_autoSwitchAddresses, rx, rx_wildcard);
  769.         }
  770.  
  771.         if (newsgroups && ss_autoSwitchNewsgroups.length > 0)
  772.         {
  773.             rx = "[a-zA-Z0-9][a-zA-Z0-9_.-]*";
  774.             rx_wildcard = "[a-zA-Z0-9._-]*";
  775.  
  776.             chosenAutoSwitchSignatureForNewsgroups = ss_main.findMatchingAutoSwitchSignature(newsgroups.split(","), ss_autoSwitchNewsgroups, rx, rx_wildcard);
  777.         }
  778.  
  779.         if (mailinglists.length > 0 && ss_autoSwitchMailinglists.length > 0)
  780.         {
  781.             rx = "[:alnum:]*";
  782.             rx_wildcard = "[:alnum:]*";
  783.  
  784.             chosenAutoSwitchSignatureForMailinglists = ss_main.findMatchingAutoSwitchSignature(mailinglists, ss_autoSwitchMailinglists, rx, rx_wildcard);
  785.         }
  786.  
  787.         if ( chosenAutoSwitchSignatureForAddresses    > -1 ||
  788.              chosenAutoSwitchSignatureForNewsgroups   > -1 ||
  789.              chosenAutoSwitchSignatureForMailinglists > -1  )
  790.         {
  791.             for (var j = 0; j < priority.length; j++)
  792.             {
  793.                 switch (priority.charAt(j))
  794.                 {
  795.                     case "A":
  796.                       if (chosenAutoSwitchSignatureForAddresses > -1)
  797.                       {
  798.                           ss_main.loadSignature(chosenAutoSwitchSignatureForAddresses, true);
  799.                           return true;
  800.                       }
  801.                       break;
  802.  
  803.                     case "N":
  804.                       if (chosenAutoSwitchSignatureForNewsgroups > -1)
  805.                       {
  806.                           ss_main.loadSignature(chosenAutoSwitchSignatureForNewsgroups, true);
  807.                           return true;
  808.                       }
  809.                       break;
  810.  
  811.                     case "M":
  812.                       if (chosenAutoSwitchSignatureForMailinglists > -1)
  813.                       {
  814.                           ss_main.loadSignature(chosenAutoSwitchSignatureForMailinglists, true);
  815.                           return true;
  816.                       }
  817.                       break;
  818.                 }
  819.             }
  820.         }
  821.  
  822.         return false;
  823.     },
  824.  
  825.     getAddressesFromCompField : function(compField)
  826.     {
  827.         var addresses = new Array();
  828.  
  829.         var parser = Components.classes["@mozilla.org/messenger/headerparser;1"].getService(Components.interfaces.nsIMsgHeaderParser);
  830.         var addressCount = parser.parseHeadersWithArray(compField, addresses, [], []);
  831.  
  832.         // transform array of PRUnichar* into array with normal strings
  833.         for (var i = 0; i < addressCount; i++)
  834.         {
  835.             addresses[i] = addresses.value[i];
  836.         }
  837.  
  838.         return addresses;
  839.     },
  840.  
  841.     findMatchingAutoSwitchSignature : function(inputValues, autoSwitchTriggers, regEx, regExWildcard)
  842.     {
  843.         var inputValue;
  844.  
  845.         var autoSwitchTrigger;
  846.         var autoSwitchTriggerRegEx;
  847.  
  848.         var validate = new RegExp(regEx);
  849.  
  850.         for (var i = 0; i < inputValues.length; i++)
  851.         {
  852.             inputValue = inputValues[i];
  853.  
  854.             if (validate.test(inputValue))
  855.             {
  856.                 for (var j = 0; j < autoSwitchTriggers.length; j++)
  857.                 {
  858.                     autoSwitchTrigger = autoSwitchTriggers[j].split(";");
  859.  
  860.                     for (var k = 0; k < autoSwitchTrigger.length; k++)
  861.                     {
  862.                         if (autoSwitchTrigger[k].indexOf("?") > -1)
  863.                         {
  864.                             autoSwitchTriggerRegEx = new RegExp(autoSwitchTrigger[k].split("?").join(regExWildcard));
  865.                             match = autoSwitchTriggerRegEx.test(inputValue);
  866.                         }
  867.                         else
  868.                         {
  869.                             match = (autoSwitchTrigger[k].toLowerCase() == inputValue.toLowerCase());
  870.                         }
  871.  
  872.                         if (match)
  873.                             return j;
  874.                     }
  875.                 }
  876.             }
  877.         }
  878.  
  879.         return -1;
  880.     },
  881.  
  882.     checkAutoSwitchArray : function(autoSwitchArray)
  883.     {
  884.         for (var i = 0; i < autoSwitchArray.length; i++)
  885.         {
  886.             if (autoSwitchArray[i].length > 1)
  887.                 return true;
  888.         }
  889.  
  890.         return false;
  891.     },
  892.  
  893.     dehybrid : function(hybridString)
  894.     {
  895.         var hybridSeparator = hybridString.indexOf("\n=\n");
  896.  
  897.         if (hybridSeparator > -1)
  898.         {
  899.             var plainPart = hybridString.substring(0, hybridSeparator);
  900.             var htmlPart = hybridString.substr(hybridSeparator + 3);
  901.  
  902.             return ((GetCurrentEditorType() == "textmail") ? plainPart : htmlPart);
  903.         }
  904.  
  905.         return hybridString;
  906.     },
  907.  
  908.     dump : function(str)
  909.     {
  910.         var csClass = Components.classes['@mozilla.org/consoleservice;1'];
  911.         var cs = csClass.getService(Components.interfaces.nsIConsoleService);
  912.  
  913.         cs.logStringMessage((new Date()).getTime() + ": " + str);
  914.     }
  915. };
  916.  
  917. window.addEventListener("load", ss_main.onLoad, true);
  918. window.addEventListener("compose-window-close", ss_main.sanitize, true);
  919. window.addEventListener("compose-window-reopen", ss_main.init, true);
  920. window.addEventListener("compose-from-changed", ss_main.fromChanged, true);
  921.